//  this library.
import 'dart:async';
import 'dart:convert';
import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hktk_app/config/storage_key.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:intl/intl.dart';
import 'package:hktk_app/widget/home/table_calendar.dart';
import 'package:table_calendar/table_calendar.dart';

class CalendarPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _CalendarPageState();
}

class _CalendarPageState extends State<CalendarPage> {
  String btn_text = "编辑";
  late Future<dynamic> _list;
  bool enabledText = false;
  // late String examName = "";
  late String examDate = "";
  DateTime? _selectedDay = DateTime.now();
  late TextEditingController _textController = TextEditingController();
  late StreamController<List<dynamic>?> _streamController1 ;
  late StreamController<List<String?>> _streamController2 ;

  // selectedDay是utc时间
  void _onDateSelected(DateTime? selectedDay, List<dynamic>? e) {
    // examName = "";

    if (e != null && e.isNotEmpty) {
      List<String?> list = [];
      for (int i = 0; i < e.length; i++) {
        Map<String, dynamic> map = e[i];
        if (DateFormat("yyyy-MM-dd").parse(map["examDate"]).toUtc() ==
            selectedDay) {
          list.add(map["examName"]);
        }
      }
      // 不管list是否为空，都要回调_streamController2监听
      _streamController2.add(list);
    }
    // setState(() {
    //   _selectedDay = selectedDay;
    // });
    // _textController.text = HiCache.getInstance().get("calendar" + _selectedDay.toString().split(" ")[0]) ?? "";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      appBar: AppBar(
        title: Text("考试日历"),
        actions: [
          IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: Icon(Icons.close),
          ),
        ],
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              FutureBuilder(
                  future: _list,
                  builder: (BuildContext context, AsyncSnapshot snapshot) {
                    if (snapshot.connectionState == ConnectionState.done) {
                      var list = snapshot.data;

                      if (list != null && (list as List).isNotEmpty) {
                        List<String?> list1 = [];
                        for (int i = 0; i < list.length; i++) {
                          // 如果刚好选中的这天有考试，要显示出来
                          if (isSameDay(_selectedDay,
                              DateFormat("yyyy-MM-dd")
                                  .parse(list[i]["examDate"] as String))) {
                            list1.add(list[i]["examName"] as String);
                          }
                        }
                        _streamController2.add(list1);
                      }
                      return TableCalendarWidget(
                          onDateSelected: _onDateSelected,
                          initDate: _selectedDay!,
                          examList: list,
                          controller: _streamController1);
                    } else
                      return Container();
                  }),

              // SizedBox(height: 20),
              // TextField(
              //   enabled: enabledText,
              //   maxLines: 4,
              //   controller: _textController,
              //   decoration: const InputDecoration(
              //     hintText: '输入内容',
              //     border: OutlineInputBorder(),
              //   ),
              // ),
              // SizedBox(height: 20),
              Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    // ElevatedButton(
                    //   onPressed: () {
                    //     if (btn_text == '保存') {
                    //       // debugPrint(_selectedDay.toString());
                    //       if(_textController.text!=null||_textController.text!=""){
                    //         //
                    //         List list=_selectedDay.toString().split(" ");
                    //         // _addEvent();
                    //         String? dateList=HiCache.getInstance().get(StorageKey.saveCalendarKey);
                    //         List l=[];
                    //         if(dateList==null){
                    //           HiCache.getInstance().setStringList(StorageKey.saveCalendarKey, [list[0]]);
                    //         }else{
                    //           l.add(list[0]);
                    //           l.addAll((json.decode(dateList) as List).toSet().toList());
                    //           HiCache.getInstance().setString(StorageKey.saveCalendarKey,json.encode(l));
                    //           // HiCache.getInstance().setStringList(StorageKey.saveCalendarKey,l as List<String>);
                    //         }
                    //         HiCache.getInstance().setString("calendar" + list[0], _textController.text);
                    //         setState(() {
                    //           //
                    //           btn_text = "编辑";
                    //           enabledText = false;
                    //         });
                    //       }
                    //
                    //     } else {
                    //       setState(() {
                    //         enabledText = true;
                    //         btn_text = "保存";
                    //       });
                    //     }
                    //   },
                    //   child: Text(btn_text),
                    // ),
                    // SizedBox(width: 20),
                    // ElevatedButton(
                    //   onPressed: () {
                    //     //   清除日历缓存
                    //     String? dateList=HiCache.getInstance().get(StorageKey.saveCalendarKey);
                    //     if(dateList!=null){
                    //       List list=(json.decode(dateList) as List);
                    //       for(var i=0;i<list.length;i++){
                    //         HiCache.getInstance().remove("calendar"+list[i]);
                    //       }
                    //       HiCache.getInstance().remove(StorageKey.saveCalendarKey);
                    //       setState(() {
                    //
                    //       });
                    //     }
                    //   },
                    //   child: Text("清除记录"),
                    // )
                  ]),

              _ExamText(
                examName: "",
                examDate: examDate,
                controller: _streamController2,
              ),
              SizedBox(
                  height:
                      MediaQuery.of(context).viewInsets.bottom), // 确保底部有足够的空间
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _streamController1 =
        StreamController<List<dynamic>?>();
    _streamController2 =
        StreamController<List<String?>>();
    // 初始化获取考试日历
    DateTime now = DateTime.now();
    _list = MyDao.getCalendar(now.year, now.month);

    // 在生命周期里监听，和在回调方法里调用controller相比，生命周期里add时并未触发listen，原因不明，可能是嵌套controller会有bug？
    _streamController1.stream.listen((e) {
      //   控制controller2改变显示,
      // 这里只考虑了一天一考试
      _streamController2.add(e!.map((ele){
        return ele["examName"] as String;
      }).toList());
    });
  }

  @override
  void dispose() {
    super.dispose();
    _textController.dispose();
    _streamController1.close();
    _streamController2.close();
  }
}

class _ExamText extends StatefulWidget {
  final StreamController<List<String?>> controller;
  final String examName;
  final String examDate;

  _ExamText(
      {Key? key,
      required this.examName,
      required this.examDate,
      required this.controller})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => _createExamState();
}

class _createExamState extends State<_ExamText> {
  late String _examName = "";
  late String _examDate = "";
  late List<String?> _examNameList = [];

  @override
  void initState() {
    super.initState();
    widget.controller.stream.listen((e) {
      setState(() {
        _examNameList = e;
        // _examDate = e["examDate"] ?? "";
        // _examName = e["examName"] ?? "";
      });
    });
  }
  @override
  void dispose() {
    //   dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (_examNameList.isNotEmpty) {
      return Column(
        spacing: 10,
        children: [
          for (var item in _examNameList)
            Container(
              padding: EdgeInsets.only(left: 30, right: 30),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "考试名称：",
                    style: TextStyle(fontSize: 20),
                  ),
                  Text(
                    item!,
                    style: TextStyle(fontSize: 20),
                  )
                ],
              ),
            )
        ],
      );
    }
    return Container();
  }
}
